﻿/*
 * PsTFS is a set of PowerShell commands to manage and use Team Foundation Server. PowerShell 
 * effectiveness is combined with the power of TFS API to maximizes TFS capabilities.
 * 
 * Creator : Choulant Noham
 * Mail : choulant@gmail.com
 * Blog : http://choulant.blogspot.com
 * 
 */

using System;
using System.Collections;
using System.Linq;
using System.Management.Automation;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using PsTFS.Methodes;
using PsTFS.Objects;

namespace PsTFS.Commandes.Get
{
    /// <summary>
    /// Permet l'éxcution d'une requete
    /// </summary>
    [Cmdlet(VerbsCommon.Get, "WIs")]
    public class GetWIs: PsCmdlet
    {
        /// <summary>
        /// Constructeur et initialisation des données
        /// </summary>
        public GetWIs()
        {
            StoredQuery = string.Empty;
            Query = string.Empty;
        }

        /// <summary>
        /// Lancement du processus
        /// </summary>
        protected override void ProcessRecord()
        {
            try
            {
                string project = string.Empty;

                if (Context.Instance.Project != null)
                    project = Context.Instance.Project.Name;

                WorkItemCollection workItems = null;
                if (!string.IsNullOrEmpty(project))
                {
                    if (!string.IsNullOrEmpty(StoredQuery))
                    {
                        var x = Context.Instance.WorkItemStore.Projects[project].QueryHierarchy as QueryItem;
                        var qry = x.Traverse(p => (p as QueryFolder), TraverseType.PreOrder).FirstOrDefault(q => q.Path == StoredQuery);
                        if (qry == null)
                        {
                            var err = ErrorRecord(new NullReferenceException(StoredQuery + " is not a stored query."), ErrorCategory.WriteError);
                            WriteError(err);
                        }
                        else
                        {
                            var qd = Context.Instance.WorkItemStore.GetQueryDefinition(qry.Id);
                            // Add Project to query parameters if it's not already there
                            if (QueryParameters == null)
                            {
                                qd.QueryText = qd.QueryText.Replace("@project", "'" + ProjectName + "'");
                            }
                            workItems = Context.Instance.WorkItemStore.Query(qd.QueryText, QueryParameters);
                        }
                    }
                    else
                    {
                        workItems = Context.Instance.WorkItemStore.Query("Select [System.ID] from WorkItem WHERE [System.TeamProject] = '" + project + "'");
                    }
                }
                else if (!string.IsNullOrEmpty(Query))
                {
                    workItems = Context.Instance.WorkItemStore.Query(Query);
                }
                else
                {
                    workItems = Context.Instance.WorkItemStore.Query("Select [System.ID] from WorkItem");
                }

                //Retourne l'assembly compilée
                // ReSharper disable AssignNullToNotNullAttribute
                WriteObject(workItems.Cast<WorkItem>().ToList(), false);
                // ReSharper restore AssignNullToNotNullAttribute
            }
            catch (PsTFSException ex)
            {
                var err = ErrorRecord(ex, ErrorCategory.WriteError);
                WriteError(err);
                Log.AddLog(null, ex.StackTrace);
            }
            finally
            {
                base.ProcessRecord();
            }

        }

        /// <summary>
        /// Permet d'informer la fin de la commande
        /// </summary>
        protected override void EndProcessing()
        {
            Log.AddLog(null, "Get-WIs is end");
            base.EndProcessing();
        }
        /// <summary>
        /// Object contenant Team Foundation Server
        /// </summary>
        [Parameter(Position = 0)]
        public TfsTeamProjectCollection TFS
        {
            set { Context.Instance.TFS = value; }
        }

        /// <summary>
        /// Nom du label
        /// </summary>
        [Parameter(Position = 1)]
        [ValidateNotNullOrEmpty]
        public string ProjectName
        {
            get { return Context.Instance.Project != null ? Context.Instance.Project.Name : String.Empty; }
            set { Context.Instance.SetProject(value); }
        }

        /// <summary>
        /// Requête pour la récupération de WI
        /// </summary>
        [Parameter(Position = 2)]
        [ValidateNotNullOrEmpty]
        public String Query { get; set; }

        /// <summary>
        /// Nom de la procedure de WI
        /// </summary>
        [Parameter(Position = 3)]
        [ValidateNotNullOrEmpty]
        public String StoredQuery { get; set; }

        [Parameter(Position = 4)]
        [ValidateNotNullOrEmpty]
        public Hashtable QueryParameters { get; set; }

        public String FormattedQuery
        {
            get
            {
                // If the query starts with «, then it's a 2013-formatted query and just pass it thru
                if (StoredQuery.StartsWith("«")) return StoredQuery;

                // if not, then figure out the path so it can be formatted.
                var path = System.IO.Path.GetDirectoryName(StoredQuery) ?? String.Empty;
                if (System.IO.Path.IsPathRooted(StoredQuery))
                {
                    path = path.Substring(1);
                }
                var query = System.IO.Path.GetFileName(StoredQuery);

                return String.IsNullOrEmpty(path)
                           ? StoredQuery
                           : "«" + path.Replace("\\", "⁄").Replace("/", "⁄") + "» " + query;
            }
        }
    }
}